package com.tcs.test.aop;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tcs.test.redis.RedisAn;

import net.sf.json.JSONObject;

@Aspect
public class ClassAspect {
	
	private final Logger logger = LoggerFactory.getLogger(ClassAspect.class);
	
	@Pointcut("execution(* com.tcs.test.aop.service.*.*(..))")
    public void pointcutName(){}

	/**
	* @Title: performance  
	* @Description: 之前
	* @param     参数  
	* @return void    返回类型  
	 */
//    @Before("pointcutName()")
//    public void performance(){
//    	logger.debug(" 在之前!! ");
//        System.out.println("Spring AOP");
//    }
    
    @Around("pointcutName()")
    public Object processTx(ProceedingJoinPoint jp) throws Throwable {
    	MethodSignature methodSignature = (MethodSignature)jp.getSignature();
		Method targetMethod = methodSignature.getMethod();
		Class<? extends Method> clazz = targetMethod.getClass();
		
		String parmas = methodSignature.getParameterNames()[0];
		
		String className = jp.getTarget().getClass().getName();
		Field[] field = jp.getTarget().getClass().getDeclaredFields();
		String key = className + targetMethod.getName() + Arrays.toString(jp.getArgs());
		String returnType = targetMethod.getReturnType().getName();
		
//		logger.debug(" field : {} " , field.get(jp.getTarget().getClass()));
		logger.debug("methodName : {} , params : {} , paramsName : {} ,className : {} ,field : {} , key : {} , returnType : {} " , targetMethod.getName(),jp.getArgs() , parmas , className , field , key , returnType);
		
		if (null == clazz.getAnnotation(RedisAn.class)) {
			logger.debug(" 读取缓存!");
		} else {
			logger.debug(" 没有 redis 注解!");
		}
		
		Object result = jp.proceed();
		String jsonStr = JSONObject.fromObject(result).toString();
		
		JSONObject resultJson = JSONObject.fromObject(jsonStr);
		Object obj = JSONObject.toBean(resultJson,targetMethod.getReturnType());
		
		logger.debug("result : {}  , obj : {} " , jsonStr , obj);
		return result;
    }
}